<?php namespace App\Http\Controllers\Auth;

use Log;

class YRDauth {

    const HOST = 'http://10.106.4.239:80';
    public function __construct() {
        //self::host = 'https://api.douban.com/v2/book';
    }
    /**
     * curl get
     * @access public
     * @param string $url    请求链接
     * @param array  $params 请求参数
     * @return Json
     */
    private static function simple_get($url,$params){


        $url = urldecode($url.($params ? '?'.http_build_query($params, NULL, '&') :''));

        $ch = curl_init(); //初始化curl
        curl_setopt($ch, CURLOPT_URL, $url);//设置链接
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//设置是否返回信息
        curl_setopt($ch, CURLOPT_HEADER, 0);
        $output = curl_exec($ch);
        curl_close($ch);


        return $output;
    }
    /**
     * curl post
     * @access public
     * @param string $url    请求链接
     * @param array  $params 请求参数
     * @return Json
     */
    private static function simple_post($url,$params){

        $header = array("Content-type"=>'text/xml',"charset"=>"UTF-8");//定义content-type为xml
        //$header = "Content-type: text/xml";//定义content-type为xml
        $ch = curl_init(); //初始化curl
        curl_setopt($ch, CURLOPT_URL, $url);//设置链接
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//设置是否返回信息
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);//设置HTTP头
        curl_setopt($ch, CURLOPT_POST, 1);//设置为POST方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);//POST数据
        $output = curl_exec($ch);//接收返回信息

        if(curl_errno($ch)){//出错则显示错误信息
            echo 'Curl error: ' . curl_error($ch);exit;
        }
        curl_close($ch); //关闭curl链接

        return $output;
    }

    public function  getBookByISBN($isbn) {
        $url = self::HOST.'/isbn/'.$isbn;
        $params = array();
        $bookinfo = self::simple_get($url,$params);
        //$r = json_decode($bookinfo);
        //dd($r->rating->max);exit;
        return json_decode($bookinfo);
    }

    public function checkYrdUser($email,$password) {
        Log::info('checkYrdUser():'.$email.'===='.$password);
        $params['username'] = $email;
        $params['password'] = $password;
        $new_parames = http_build_query($params);
        // 模拟返回结果：
//        return true;
        //$result = self::simple_post(self::HOST, $params);dd($result);
        $result = self::simple_post(self::HOST, $new_parames);
//        if($email=='jianzhong3@creditease.cn') {
//            dd($params,$result);
//        }

        $res = json_decode($result);
        if($res->ret_code==0) {
            //Log::info('ldap验证通过：'. $res);
            return true;
        }else {
            //Log::info('ldap验证失败：'. $res);
            return false;
        }
    }

    public function t()
    {
        return 'ok';
    }
}